// 3.3 获取配置(可选)
use reqwest::Client;
use serde::{Deserialize, Serialize};
use crate::api::get_stream_token::get_stream_token;
use crate::api::get_session_id::get_session_id;
use anyhow::{Result, anyhow};
use crate::api::get_session_status::get_session_status;

/* 返回主机的网络地址 */
pub struct session_config{
    pub ipv4_address: String,
    pub ipv4_port: u16,
    pub ipv6_address: Option<String>,
    pub ipv6_port: u16,
}

#[derive(Debug, Serialize, Deserialize)]
struct response {
    keepAlivePulseInSeconds: u32,
    serverDetails: ServerDetails,
}

#[derive(Debug, Serialize, Deserialize)]
struct ServerDetails {
    ipAddress: String,
    port: u16,
    ipV4Address: String,
    ipV4Port: u16,
    ipV6Address: Option<String>,
    ipV6Port: u16,
    iceExchangePath: String,
    stunServerAddress: Option<String>,
    srtp: Srtp,
}

#[derive(Debug, Serialize, Deserialize)]
struct Srtp {
    key: String,
}

pub async fn get_session_config() -> Result<session_config>{
    // 等待会话状态为Provisioned
    get_session_status().await.unwrap();
    let client = Client::new();
    let session_id = get_session_id(None).await.unwrap();
    let url = format!("https://uks.core.gssv-play-prodxhome.xboxlive.com/v5/sessions/home/{}/configuration",session_id);
    let Authorization = format!("Bearer {}",get_stream_token().await.unwrap());

    let response = client.get(url)
        .header("Content-Type", "application/json")
        .header("Authorization", Authorization)
        .send().await.unwrap();
    let response_code = response.status().as_u16();
    let response_text = response.text().await.unwrap();
    match response_code {
        200 => {
            let response: response = serde_json::from_str(&response_text).unwrap();
            let session_config = session_config{
                ipv4_address: response.serverDetails.ipV4Address,
                ipv4_port: response.serverDetails.ipV4Port,
                ipv6_address: response.serverDetails.ipV6Address,
                ipv6_port: response.serverDetails.ipV6Port,
            };
            return Ok(session_config);
        }
        _ => {
            return Err(anyhow!("failed to get session config, response code: {response_code}"));
        }
    }
}


